package com.luli.controllor;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.luli.Utils.EncryptUtils;
import com.luli.Utils.ReportPropsConf;
import com.luli.dao.UsersDao;
import com.luli.entity.UserData.QueryUserParam;
import com.luli.entity.UserData.UpdateUserParam;
import com.luli.entity.Users;
import com.luli.entity.poi.ExcelDownloadPath;
import com.luli.entity.poi.ExportExcel;
import com.luli.entity.response.ResponseMsg;
import com.luli.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.luli.Utils.EncryptUtils.getReportTmpPaths;
import static com.luli.Utils.ResponseMsgUtil.getFailMsg;
import static com.luli.Utils.ResponseMsgUtil.getSuccessMsg;
import static com.luli.enumeration.MessageEnum.DEL_USER_ERRORS;

/**
 * 陆离
 * 2022/5/3 1:41:34
 */
@RestController
@Slf4j
@RequestMapping("/test")
@CrossOrigin
public class UsersController {
    private final Logger logger = LoggerFactory.getLogger(UsersController.class);


    @Autowired
    private UsersService usersService;

    @Autowired
    private ReportPropsConf reportPropsConf;
    @Autowired
    private UsersDao usersDao;
    @Value("${test.ta}")
    private String test;

    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    public ResponseMsg<?> getUser(String userName) {
        try {
            log.info("请求用户", userName);
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("test", test);
            log.info("test====" + JSON.toJSONString(map));
            //获取到数据
            List<Users> users = usersService.getUsers(userName);
            return getSuccessMsg(null, "查询成功", users);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return getFailMsg(null, "查询失败", e.getMessage());
        }
    }

    @RequestMapping(value = "/updateUser", method = RequestMethod.GET)
    @Transactional(rollbackFor = Exception.class)
    public ResponseMsg<?> updateUser(String age, String account) {
        usersService.updateUserService(age, account);
        return getSuccessMsg(null, "查询成功", null);

    }

    @RequestMapping(value = "/getUserData", method = RequestMethod.POST)
    public ResponseMsg<?> getUserData(String userName) {
        try {
            log.info("请求用户", userName);
            //获取到数据
            List<Users> users = usersService.getUsers(userName);
            return getSuccessMsg(null, "查询成功", users);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return getFailMsg(null, "查询失败", e.getMessage());
        }
    }

    /**
     * 127.0.0.1:8082/test/downloadUserData
     * Excel导出
     *
     * @param request
     * @param response
     * @param userName
     * @return
     */
    @RequestMapping(value = "/downloadUserData", method = RequestMethod.GET)
    public ResponseMsg<?> downloadUserData(HttpServletRequest request, HttpServletResponse response, String userName) {
        try {
            log.info("请求用户", userName);
            ExportExcel exportExcel = usersService.downloadExcelGetUsers(userName);
            String reportTmpPaths = getReportTmpPaths(reportPropsConf);
            EncryptUtils.encryAndExportByResponseList(request, response, exportExcel.export(reportTmpPaths), reportPropsConf);
            return getSuccessMsg(null, "导出成功,已输出到：" + reportTmpPaths, null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return getFailMsg(null, "导出失败", e.getMessage());
        }
    }

    @Autowired
    private ExcelDownloadPath excelDownloadPath;

    /**
     * 批量导入
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/importExcelData", method = RequestMethod.POST)
    public ResponseMsg<?> importExcel(MultipartFile file, HttpServletRequest request) throws Exception {
        try {
//            String filePath = request.getSession().getServletContext().getRealPath(File.separator) + "ImportExcel" + File.separator;
            String filePath = excelDownloadPath.getFilePath();
            logger.info("上传文件路径为: {}", filePath);
            return usersService.importExcel(file, filePath);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return getFailMsg(null, "导入失败", e.getMessage());
        }
    }


    @RequestMapping(value = "/getUsetPageTest", method = RequestMethod.POST)
    public ResponseMsg<?> getUsetPageTest(@RequestBody QueryUserParam queryUserParam) {
        try {
            log.info("请求用户", queryUserParam);
            //获取到数据
            PageInfo<Users> usersPageTest = usersService.getUsersPageTest(queryUserParam.getUserName(), queryUserParam.getPageNum(), queryUserParam.getPageSize(),
                    queryUserParam.getSex());
            return getSuccessMsg(null, "查询成功", usersPageTest);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return getFailMsg(null, "查询失败", e.getMessage());
        }
    }

    /**
     * 删除用户
     *
     * @param account
     * @return
     */
    @RequestMapping(value = "/delUser", method = RequestMethod.GET)
    public ResponseMsg<?> delUser(@RequestParam String account) {
        try {
            return usersService.delUser(account);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return getFailMsg(DEL_USER_ERRORS.getCode(), DEL_USER_ERRORS.getMsg(), e.getMessage());
        }
    }

    /**
     * 修改用户信息
     *
     * @param updateUserParam
     * @return
     */
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public ResponseMsg<?> updateUser(@RequestBody UpdateUserParam updateUserParam) {
        try {
            //获取到数据
            return usersService.updateUser(updateUserParam);
        } catch (Exception e) {
            return getFailMsg(DEL_USER_ERRORS.getCode(), DEL_USER_ERRORS.getMsg(), e.getMessage());
        }
    }


    @RequestMapping(value = "/downloadUser", method = RequestMethod.POST)
    public ResponseMsg<?> downloadUser(HttpServletRequest request, HttpServletResponse response, String userName) {
        try {
            log.info("请求用户", userName);
            ExportExcel exportExcel = usersService.downloadExcelUsers(userName);
            String reportTmpPaths = getReportTmpPaths(reportPropsConf);
            EncryptUtils.encryAndExportByResponseList(request, response, exportExcel.export(reportTmpPaths), reportPropsConf);
            log.info("文件已经导出到{}", reportTmpPaths);
            return getSuccessMsg(null, "导出成功,已输出到：" + reportTmpPaths, null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return getFailMsg(null, "导出失败", e.getMessage());
        }
    }

    //127.0.0.1:8086/LuLi/test/downloadUserSheets
    @RequestMapping(value = "/downloadUserSheets", method = RequestMethod.GET)
    public ResponseMsg<?> downloadUserSheets(HttpServletRequest request, HttpServletResponse response, String userName) {
        try {
            log.info("请求用户", userName);
            ExportExcel exportExcel = usersService.downloadExcelGetUsersSheets(userName);
            String reportTmpPaths = getReportTmpPaths(reportPropsConf);
            EncryptUtils.encryAndExportByResponseList(request, response, exportExcel.export(reportTmpPaths), reportPropsConf);
            log.info("文件已经导出到{}", reportTmpPaths);
            return getSuccessMsg(null, "导出成功,已输出到：" + reportTmpPaths, null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return getFailMsg(null, "导出失败", e.getMessage());
        }
    }


}
